package dat255.calendarclock.controller;

import java.util.Calendar;
import java.util.Observable;

import android.os.Handler;

public class SecondTimer extends Observable {

	// Field

	private static SecondTimer singleInstance;

	private Handler handler = new Handler();

	private Runnable runnable = new Runnable() {
		@Override
		public void run() {
			setChanged();
			notifyObservers();
			handler.postDelayed(this, 1000);
		}
	};

	// Constructor

	private SecondTimer() {

		Calendar calendar = Calendar.getInstance();
		long currentTimestamp = calendar.getTimeInMillis();
		calendar.roll(Calendar.MILLISECOND, true);
		long diffTimestamp = calendar.getTimeInMillis() - currentTimestamp;
		long myDelay = (diffTimestamp < 0 ? 0 : diffTimestamp);
		handler.postAtTime(runnable, myDelay);

	}

	public static SecondTimer getInstance() {
		if (singleInstance == null)
			singleInstance = new SecondTimer();
		return singleInstance;
	}

}
